<template>
  <div class="cart">
    <div class="header">
      <span>购物车</span>
    </div>

    <van-empty image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png" image-size="80"
      description="购物车为空, 请选购商品" v-if="store.totalAmount === 0" />

    <template v-else>
      <van-swipe-cell v-for="item in store.cart" :key="item.id">
        <van-card :price="formatMoney(item.price_low)" :title="item.project_name" class="goods-card">
          <template #num>
            <van-stepper :modelValue="item.amount" @change="handleModifyAmount(item.id, $event)" theme="round"
              button-size="22" />
          </template>
          <template #thumb>
            <van-checkbox v-model="item.checked"></van-checkbox>
            <div class="van-image" style="width: 100%; height: 100%;">
              <img :src="baseURL + item.cover" class="van-image__img" style="object-fit: cover;">
            </div>
          </template>
        </van-card>
        <template #right>
          <van-button square text="删除" type="danger" class="delete-button" @click="handleRemoveFromCart(item.id)" />
        </template>
      </van-swipe-cell>

      <!-- 提交订单栏 -->
      <van-submit-bar :price="store.totalMoney" button-text="提交订单" @submit="jumpToConfirm">
        <van-checkbox :modelValue="store.allChecked" @click="handleToggleAllChecked">全选</van-checkbox>
      </van-submit-bar>
    </template>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref } from 'vue'
import useCartStore from '../../store/cart'
import { baseURL } from '../../apis/Ajax';
const router = useRouter()
const store = useCartStore()

// 删除商品
function handleRemoveFromCart(id) {
  store.removeFromCart(id)
}

// 修改购物车中商品数量
function handleModifyAmount(id, value) {
  store.modifyAmount(id, value)
}

// 切换全选
function handleToggleAllChecked() {
  store.toggleAllChecked(!store.allChecked)
}

// 跳转到体检订单界面
function jumpToConfirm() {
  router.push('/confirm')
}

//  格式化商品金额
const formatMoney = (val) => {
  return (Number(val)).toFixed(2)
}

</script>
<style lang="less" scoped>
@import '../../style/common.less';

.header {
  width: 100%;
  height: 48px;
  text-align: center;
  font-size: .9rem;
  color: white;
  line-height: 48px;
  background-image: linear-gradient(to top, @c03, @c05);

  >span {
    padding-left: 10px;
  }
}

.van-card {
  font-size: 16px;
  display: flex;
  justify-content: space-between;
}

.van-card[data-v-59435644] {
  height: 120px;
}

.goods-card {
  background-color: white;
}

/deep/ .van-card__title {
  margin-top: 20px;
}

/deep/ .van-card__content {
  width: 260px;
}

.checklist {

  display: block;
}

.van-empty {
  margin-top: 200px;
}

.delete-button {
  height: 100%;
}

.van-submit-bar {
  margin-bottom: 50px;
}
</style>